package cn.supermarket.framework.security.handler;

import cn.supermarket.common.contant.Constants;
import cn.supermarket.common.core.entity.LoginUser;
import cn.supermarket.common.utils.MessageUtils;
import cn.supermarket.common.utils.StringUtils;
import cn.supermarket.framework.manager.AsyncManager;
import cn.supermarket.framework.manager.factory.AsyncFactory;
import cn.supermarket.framework.web.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author yp
 * @Date 2024/5/28:10:52
 */
@Component
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        LoginUser loginUser=tokenService.getLoginUser(request);
        if(StringUtils.isNotNull(loginUser)){
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
        }
    }
}
